#pragma once
#include <sys/types.h>
#include <sys/ipc.h>
#include <string>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <iostream>
#include "Comm.hpp"
const std::string pathname = ".";
const int projid = 0x66;
const int gmode = 0666;
const size_t gsize = 4096;
#define CREATER "creater"
#define USER "user"

class Shm
{

private:
    void CraeteHelper(int shmflg)
    {
        _shmid = shmget(_key, _size, shmflg);
        if (_shmid < 0)
            ERR_EXIT("shmget");
        else
            printf("shmget成功，shmid:  %d\n", _shmid);
    }

    void Create()
    {
        CraeteHelper(IPC_CREAT | IPC_EXCL | gmode);
    }
    void Get()
    {
        CraeteHelper(IPC_CREAT | gmode);
    }
    void Attach()
    {
        _start_mem = shmat(_shmid, NULL, 0);
        if (_start_mem == (void *)-1)
        {
            ERR_EXIT("shmat");
        }
    }
    void Detach()
    {
        int n = shmdt(_start_mem);
        if (n < 0)
            ERR_EXIT("shmdt");
    }
    void Destroy()
    {
        Detach();
        if (_usertype == CREATER)
        {
            int n = shmctl(_shmid, IPC_RMID, nullptr);
            if (n < 0)
            {
                ERR_EXIT("shmctl");
            }
        }
    }

public:
    Shm(const std::string &pathname, const int projid, const std::string &usertype)
        : _usertype(usertype), _size(gsize)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0)
        {
            ERR_EXIT("ftok");
        }
        if (_usertype == "creater")
        {
            Create();
        }
        if (_usertype == USER)
        {
            Get();
        }
        Attach();
    }
    ~Shm()
    {
        Destroy();
    }
    void *VirtualAddr()
    {
        return _start_mem;
    }

private:
    std::string _usertype;
    key_t _key;
    int _shmid;
    size_t _size;
    void *_start_mem;
};